	let dbName = null
	let dbPath = null
	import { renderDataBaseId, appendStorageInfo } from '@/utils/common.js'
	
	function init(dbN,dbP){
		dbName = dbN
		dbPath = dbP
	}
	/**
	 * 打开数据库 如果数据库存在则打开，不存在则创建
	 * @returns {Promise<unknown>}
	 */
	function openDb(){
		return new Promise((resolve, reject) => {
		    plus.sqlite.openDatabase({
		        name: dbName,
		        path: dbPath,
		        success: function(e){
		            resolve(e)
					appendStorageInfo('数据库打开成功/')
		        },
		        fail: function(e){
		            reject(e)
					appendStorageInfo('数据库打开失败/' + JSON.stringify(e))
		        }
		    })
		})
	}
	
	/**
	 * 判断数据库是否打开 数据库已经打开则返回true，数据库没有打开则返回false
	 * @returns {boolean}
	 */
	 function isOpen(){
	    const openStatus = plus.sqlite.isOpenDatabase({
	        name: dbName,
	        path: dbPath
	    })
		return openStatus
	}
	
	 /**
	 * 关闭数据库   完成数据库操作后，必须关闭数据库，否则可能会导致系统资源无法释放。
	 * @returns {Promise<unknown>}
	 */
	function closeDb() {
		return new Promise((resolve, reject) => {
			plus.sqlite.closeDatabase({
				name: dbName,
				success: function(e){
					console.log('数据库已自动关闭')
					resolve(e)
				},
				fail: function(e){
					console.log('数据库执行自动关闭失败')
					reject(e)
				}
			});
		})
	}
	
	/**
	 * 执行事务
	 * @param operation  需要执行的事务操作 可选值：begin（开始事务）、commit（提交）、rollback（回滚）
	 * @returns {Promise<unknown>}
	 */
	function transaction(operation){
	    return new Promise((resolve, reject) => {
	        plus.sqlite.transaction({
	            name: dbName,
	            operation: operation,
	            success: function(e){
	                resolve(e)
	            },
	            fail: function(e){
	                reject(e)
	            }
	        });
	    })
	}
	
	/**
	 * 执行增删改等操作的SQL语句
	 * @param sql 需要执行的SQL语句
	 * @returns {Promise<unknown>}
	 */
	async function executeSql(sql) {
		if(!isOpen()){
			await openDb()
		}
	    const result = await new Promise((resolve, reject) => {
	        plus.sqlite.executeSql({
	            name: dbName,
	            sql: sql,
	            success: function(e){
	                resolve(e)
					afterOneMinuteCloseDb();
	            },
	            fail: function(e){
					console.log(e)
	                reject(e)
					afterOneMinuteCloseDb();
	            }
	        })
	    })
		return result
	}
	
	/**
	 * 保存
	 * @param {String} tableName
	 * @param {Object} data
	 */
	async function insert(tableName,data) {
		const sql = genInsertSql(tableName,data)
		await executeSql(sql)
		const res = await getLastId();
		return res
	}
	
	/**
	 * 更新
	 * @param {String} tableName
	 * @param {Object} data
	 * @param {Object} where
	 */
	function update(tableName,data,where) {
		const sql = genUpdateSql(tableName,data,where)
		return executeSql(sql)
	}
	
	/**
	 * 删除
	 * @param {String} tableName
	 * @param {Object} where
	 */
	function del(tableName,where){
		const sql = genDeleteSql(tableName,where)
		return executeSql(sql)
	}
	
	// replace into
	async function replaceInto(tableName, datas){
		let data = datas.map(d => {
			const id = renderDataBaseId()
			return {
				id,
				...filterDataNull(d),
			}
		})
		let key = Object.keys(data[0]).join(',')
		let values = data.map(v => `(${Object.values(v).map(item => setValue(item)).join(',')})`).join(',')
		const sql = `replace into ${tableName} (${key}) values ${values}`;
		return await executeSql(sql)
	}
	/**
	 * 执行查询的SQL语句
	 * @param sql
	 * @returns {Promise<unknown>}
	 */
	async function selectSql(sql) {
		if(!isOpen()){
			await openDb()
		}
	    const result = await new Promise((resolve, reject) => {
	        plus.sqlite.selectSql({
	            name: dbName,
	            sql: sql,
	            success: function(data){
	                resolve(data)
					afterOneMinuteCloseDb();
	            },
	            fail: function(e){
					appendStorageInfo('数据库SelectSql查询失败/' + JSON.stringify(e))
	                reject(e)
					afterOneMinuteCloseDb();
	            }
	        })
	    })
		return result
	}
	
	/**
	 * 查询所有数据
	 * @param {Object} tableName
	 * @param {Array} fields
	 * @param {Object} where
	 */
	function findAll(tableName,fields,where,order) {
		const sql = genQuerySql(tableName,fields,where,order)
		return selectSql(sql)
	}
	
	async function pages(tableName,fields,where,order, pageObj){
		const sql = genQuerySql(tableName,fields,where,order,pageObj)
		const countSql = genCountSql(tableName,where)
		const countNum = await selectSql(countSql)
		const page = await selectSql(sql)
		return {
			content: page,
			tol: countNum[0][tableName+'_count']
		}
	}
	
	function genCountSql(tableName,where){
		let querySql = `SELECT count(1) ${tableName+'_count'} FROM ${tableName} `
		if(where){
			const whereSql = genWhereSql(where)
			querySql += ` WHERE ${whereSql} `
		} 
		return querySql
	}
	
	/**
	 * 生成保存语句
	 * @param {Object} tableName
	 * @param {Object} data
	 */
	function genInsertSql (tableName,datas){
		let key = '';
		let values = '';
		if(Array.isArray(datas)){
			let data = datas.map(d => {
				const id = renderDataBaseId()
				return {
					id,
					...filterDataNull(d),
				}
			})
			key = Object.keys(data[0]).join(',')
			values = data.map(v => `(${Object.values(v).map(item => setValue(item)).join(',')})`).join(',')
		}else{
			let data = {
				id: renderDataBaseId(),
				...filterDataNull(datas)
			}
			key = Object.keys(data).join(',')
			values = `(${Object.values(data).map(item => setValue(item)).join(',')})`
		}
		const sql = `INSERT INTO ${tableName} (${key}) VALUES ${values}`
		return sql
	}
	function setValue(value){
		if(typeof value === 'string'){
			return  "'"+value+"'"
		}
		return value
	}
	
	/**
	 * 生成更新语句
	 * @param {Object} tableName
	 * @param {Object} data
	 * @param {Object} where
	 */
	function genUpdateSql(tableName,data,where){
		const keys = Object.keys(data)
		const values = Object.values(data)
		let sqlArr = []
		for(let i=0;i<keys.length;i++){
			sqlArr.push(keys[i] + "=" + setValue(values[i]))
		}
		const dataSql = sqlArr.join(',')
		const whereSql = genWhereSql(where)
		const sql = `UPDATE ${tableName} SET ${dataSql} WHERE ${whereSql}`
		return sql
	}
	
	/**
	 * 生成删除语句
	 * @param {Object} tableName
	 * @param {Object} where
	 */
	function genDeleteSql(tableName,where){
		const whereSql = genWhereSql(where)
		const sql = `DELETE FROM ${tableName} WHERE ${whereSql}`
		return sql
	}
	
	/**
	 * 生成查询语句
	 * @param {Object} tableName
	 * @param {Object} fields
	 * @param {Object} where
	 */
	function genQuerySql(tableName,fields,where,order,page){
		let fieldSql = '*'
		if(fields){
			fieldSql = fields.join(',')
		}
		let querySql = `SELECT ${fieldSql} FROM ${tableName}`
		if(where){
			const whereSql = genWhereSql(where)
			querySql += ` WHERE ${whereSql} `
		} 
		if(order){
			const orderSql = genOrderSql(order)
			querySql += ` ORDER BY ${orderSql} `
		}
		if(page){
			querySql += ` LIMIT (${page.pageNum * page.pageSize}), ${page.pageSize}`
		}
		return querySql
	}
	
	function genOrderSql(order){
		let orderSql = []
		for(let key in order){
			orderSql.push(key + ' ' + order[key]) 
		}
		return orderSql.join(',')
	}
	
	function genWhereSql(where){
		const keys = Object.keys(where)
		const values = Object.values(where)
		let whereSql = ''
		for(let i=0;i<keys.length;i++){
			const arr = keys[i].split('_')
			const centerArr = arr.filter((_,i) => i !== 0 && i !== arr.length - 1).join('_');
			const code = getCode(arr[0],centerArr,values[i]);
			const lastArr = arr[arr.length - 1];
			if(lastArr === 'an'){
				whereSql += code + ' AND '
			}
			if(lastArr === 'or'){
				whereSql += code + ' OR '
			}
			if(lastArr === 'en'){
				whereSql += code
			}
			if(lastArr === 'anl'){
				whereSql += code + ' AND ('
			}
			if(lastArr === 'anr'){
				whereSql += code + ' ) AND'
			}
			if(lastArr === 'orl'){
				whereSql += code + ' OR ('
			}
			if(lastArr === 'orr'){
				whereSql += code + ') OR '
			}
			if(lastArr === 'enr'){
				whereSql += code + ') '
			}
		}
		return whereSql
	}
	
	/**
	 * 解析规则
	 * @param {Object} code
	 * @param {Object} key
	 * @param {Object} value
	 */
	function getCode(code,key,value){
		let data = '='
		switch(code){
			case 'eq':
				data = `${key}='${value}'`
				break
			case 'ne':
				data = `${key}!=${value}`
				break
			case 'gt':
				data = `${key}>${value}`
				break
			case 'lt':
				data = `${key}<${value}`
				break
			case 'ge':
				data = `${key}>=${value}`
				break
			case 'le':
				data = `${key}=<${value}`
				break
			case 'in':
				const inValues = value.map(item => setValue(item)).join(',')
				data = `${key} in (${inValues})`
				break
			case 'ins':
				data = `${key} in (${value})`
				break
			case 'lk':
				data = `${key} like '%${value}%'`
				break
			case 'lek':
				data = `${key} like '${value}%'`
				break
			case 'rik':
				data = `${key} like '%${value}'`
				break
		}
		return data
	}
	
	function getLastId (tableName){
		const sql = `select last_insert_rowid() as id`;
		return selectSql(sql)
	}
	
	function filterDataNull(data){
		let noNullData = {};
		Object.keys(data).map(key => {
			if(data[key] !== null && data[key] !== undefined){
				noNullData[key] = data[key];
			}
		})
		return noNullData;
	}
	function getAllTableNames(data){
		const sql = `SELECT name FROM sqlite_master WHERE type='table'`;
		return selectSql(sql)
	}
	// 
    let temp = null;
	function afterOneMinuteCloseDb(){
		clearTimeout(temp);
		temp = setTimeout(() => {
			clearTimeout(temp);
			closeDb()
		}, 1600)
	}
	export default {
		init,
		openDb,
		isOpen,
		closeDb,
		transaction,
		executeSql,
		selectSql,
		insert,
		update,
		del,
		findAll,
		pages,
		getLastId,
		replaceInto,
		getAllTableNames
	}